<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :http-request="upload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <!-- 进度条 -->
    <el-progress v-if="showProgress" class="progress" type="circle" :percentage="percentage" />
  </el-upload>
</template>

<script>
// 导入 cos 模块
const COS = require('cos-js-sdk-v5')
// 对对象存储插件进行实例化
var cos = new COS({
  SecretId: 'AKIDnQntjIcfRwA7nCLEqAF4ctue6HBpBG4c',
  SecretKey: 'HH0TgcHfneEXaMs64lBKCnBI7g04rNca'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      showProgress: false,
      percentage: 0
    }
  },
  methods: {
    upload(files) {
      // console.log(files)
      if (files.file) {
        this.showProgress = true
        cos.putObject({
          Bucket: 'zhangyurong-1308159355', // 存储桶的名称，必须
          Region: 'ap-nanjing', // 存储桶所在地域，必须字段
          Key: files.file.name, // 文件名，必须
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: files.file, // 上传文件对象
          // 上传进度条
          onProgress: (progressData) => {
            // console.log(1)
            this.percentage = progressData.percent * 100
            // console.log(JSON.stringify(progressData))
          }
        }, (err, data) => {
        // 上传成功或失败的回调
        // 当上传失败的时候,err会返回错误对象
        // 上传成功,err会返回nunll,data会返回存储的图片信息
          if (err === null) {
            this.imageUrl = `https://${data.Location}`
          }
          this.showProgress = false
        }
        )
      }
    }
  }
}

</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
